/* * @Author: 维尼小熊 * @Date: 2022-04-14 14:24:30 * @Last Modified by:
维尼小熊 * @Last Modified time: 2022-04-14 14:24:30 */
<script>
import { ElMessage } from "element-plus";
import reqVue from "../utils/req";
let flowStrategy = {
  send: sendEvent,
  save: saveEvent,
  circulated: circulatedEvent,
  back: backEvent,
  backstep: backStepEvent,
  picture: pictureEvent,
  course: courseEvent,
  end: endEvent,
  policy: policyEvent,
  export: exportEvent,
  read: readEvent,
  recycle: recycleEvent,
  cancel: cancelEvent,
};
let formData = {};
///只是查看
function readEvent(btn, that) {
  let url = that.apiEnginepath + "/v1.0/read/" + formData.taskId;
  reqVue
    .$Post(
      {
        taskId: formData.taskId,
        opinion: that.opinion == null ? "" : that.opinion.defaultValue || "",
      },
      url,
      that.way
    )
    .then(
      function(data) {
        if (data.status) {
          that.$message.success(data.message);
          setTimeout(() => {
            that.pageLoading = false;
            that.$store.commit("closeCurrentPage", that.$route.fullPath);
            that.$router.push({
              path: "/flowcenter",
              query: { callType: that.$route.query.callType },
            });
          }, 1000);
        } else {
          that.$message.error(data.message);
          that.pageLoading = false;
        }
      }.bind(that)
    );
}
///保存到待办申请
function saveEvent(btn, that) {
  that.$refs["formdata"].validate((valid) => {
    if (valid) {
      let url = that.apipath + "/v1.0/formsave/";
      reqVue.$Post(formData, url, that.way).then(
        function(data) {
          if (data.status) {
            that.$message.success(data.message);
            setTimeout(() => {
              that.pageLoading = false;
              that.$store.commit("closeCurrentPage", that.$route.fullPath);
              that.$router.push({
                path: "/flowcenter",
                query: { callType: that.$route.query.callType },
              });
            }, 1000);
          } else {
            that.$message.error(data.message);
            that.pageLoading = false;
          }
        }.bind(that)
      );
    } else {
      that.pageLoading = false;
      return false;
    }
  });
}
///发起流程
function sendEvent(btn, that) {
  that.$refs["formdata"].validate((valid) => {
    if (valid) {
      if (that.opinion != null && that.opinion.rules.length > 0) {
        that.$refs["opinion"].validate((valid) => {
          if (valid) {
            runEvent(btn, that);
          } else {
            that.pageLoading = false;
            return false;
          }
        });
      } else {
        runEvent(btn, that);
      }
    } else {
      that.pageLoading = false;
      return false;
    }
  });
}
function runEvent(btn, that) {
  let url = that.apipath + "/v1.0/formsave/";
  reqVue.$Post(formData, url, that.way).then(
    function(data) {
      if (data.status) {
        formData.taskId = data.body.currentTaskId;
        delete formData.model;
        formData.processType = 1; ///审批
        getNextNodeInfo(formData, that);
      } else {
        that.$message.error(data.message);
        that.pageLoading = false;
      }
    }.bind(that)
  );
}
///传阅
function circulatedEvent(btn, that) {
  formData.processType = 7; ///阅办
  let url = that.apiEnginepath + "/v1.0/circulatednode";
  reqVue.$Post(formData, url, that.way).then(
    function(data) {
      if (data.status) {
        dialogNodeInfoEvent(formData, that, data);
      } else {
        that.pageLoading = false;
        that.$message.error(data.message);
      }
    }.bind(that)
  );
}
///退回至第一步
function backEvent(btn, that) {
  let url = that.apiEnginepath + "/v1.0/back";
  that
    .$confirm(that.$t("i18n.confirm_back"), that.$t("i18n.confirm"), {
      type: "warning",
    })
    .then(() => {
      reqVue
        .$Post(
          {
            taskId: formData.taskId,
            opinion:
              that.opinion == null ? "" : that.opinion.defaultValue || "",
          },
          url,
          that.way
        )
        .then(
          function(data) {
            if (data.status) {
              that.$message.success(data.message);
              setTimeout(() => {
                that.pageLoading = false;
                that.$store.commit("closeCurrentPage", that.$route.fullPath);
                that.$router.push({
                  path: "/flowcenter",
                  query: { callType: that.$route.query.callType },
                });
              }, 1000);
            } else {
              that.$message.error(data.message);
              that.pageLoading = false;
            }
          }.bind(that)
        );
    });
}
///退回至具体步骤
function backStepEvent(btn, that) {
  let url = that.apiEnginepath + "/v1.0/backnodeinfo/" + formData.taskId;
  reqVue.$Post(null, url, that.way).then(
    function(data) {
      if (data.status) {
        that.$nextTick(function() {
          data.body.nextNode.forEach((element) => {
            if (element.approvalRangeType == 2) {
              element.nextStepApproverEmps = [];
              element.nextStepApproverEmpId = [];
            }
          });
          that.$refs.backnode.nextNodeInfo = data.body.nextNode;
          that.$refs.backnode.dialogNextNodeisible = true;
          that.$refs.backnode.parallelTask = data.body.judeNodeType;
          that.$refs.backnode.nextStepIds = [data.body.nextNode[0].nextStepId];
          that.$refs.backnode.nextStepId = data.body.nextNode[0].nextStepId;
        });
      } else {
        that.pageLoading = false;
        that.$message.error(data.message);
      }
    }.bind(that)
  );
}

///流程图
function pictureEvent(btn, that) {
  that.pageLoading = false;
  that.showpicturedrawer = true;
  that.$nextTick(function() {
    that.$refs.flowpicture.flowId = formData.flowId;
    that.$refs.flowpicture.flowVersionId = formData.flowVersionId;
    that.$refs.flowpicture.InitFlow();
  });
}
///过程查看
function courseEvent(btn, that) {
  that.pageLoading = false;
  that.showpicturedrawer = true;
  that.$nextTick(function() {
    that.$refs.flowpicture.flowId = formData.flowId;
    that.$refs.flowpicture.flowVersionId = formData.flowVersionId;
    that.$refs.flowpicture.taskId = formData.taskId;
    that.$refs.flowpicture.isProcesView = true;
    that.$refs.flowpicture.InitFlow();
  });
}
///终止
function endEvent(btn, that) {
  let url = that.apiEnginepath + "/v1.0/termination";

  var para = {
    opinion: that.opinion == null ? "" : that.opinion.defaultValue || "",
    taskId: formData.taskId,
  };
  that
    .$confirm(that.$t("i18n.confirm_termination"), that.$t("i18n.confirm"), {
      type: "warning",
    })
    .then(() => {
      reqVue.$Post(para, url, that.way).then(
        function(data) {
          if (data.status) {
            that.$message.success(data.message);
            setTimeout(() => {
              that.pageLoading = false;
              that.$store.commit("closeCurrentPage", that.$route.fullPath);
              that.$router.push({
                path: "/flowcenter",
                query: { callType: that.$route.query.callType },
              });
            }, 1000);
          } else {
            that.$message.error(data.message);
            that.pageLoading = false;
          }
        }.bind(that)
      );
    });
}
///导出pdf
function exportEvent(btn, that) {
  that.pageLoading = false;
  console.log(JSON.stringify(btn) + JSON.stringify(that.form));
  ElMessage({
    showClose: true,
    message: "该功能还在完善中！",
    type: "error",
  });
}

///政策
function policyEvent(btn, that) {
  that.pageLoading = false;
  console.log(JSON.stringify(btn) + JSON.stringify(that.form));
  ElMessage({
    showClose: true,
    message: "该功能还在完善中！",
    type: "error",
  });
}
//回收任务
function recycleEvent(btn, that) {
  let url = that.apiEnginepath + "/v1.0/recycling/" + formData.taskId;
  that
    .$confirm(that.$t("i18n.confirm_recycling"), that.$t("i18n.confirm"), {
      type: "warning",
    })
    .then(() => {
      reqVue.$Post(null, url, that.way).then(
        function(data) {
          if (data.status) {
            that.$message.success(data.message);
            setTimeout(() => {
              that.pageLoading = false;
              that.$store.commit("closeCurrentPage", that.$route.fullPath);
              that.$router.push({
                path: "/flowcenter",
                query: { callType: that.$route.query.callType },
              });
            }, 1000);
          } else {
            that.$message.error(data.message);
            that.pageLoading = false;
          }
        }.bind(that)
      );
    });
}
///返回按钮事件
function cancelEvent(btn, that) {
  that.$store.commit("closeCurrentPage", that.$route.fullPath);
  if (that.$route.query.callType != "instance")
    that.$router.push({
      path: "/flowcenter",
      query: { callType: that.$route.query.callType },
    });
  else
    that.$router.push({
      path: "/instance",
    });
}
///生成随机码
function createCode(codeLength) {
  var code = "";
  //设置长度，这里看需求，我这里设置了4
  //设置随机字符
  var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
  let length = codeLength == undefined ? 8 : codeLength;
  //循环codeLength 我设置的4就是循环4次
  for (var i = 0; i < length; i++) {
    //设置随机数范围,这设置为0 ~ 36
    var index = Math.floor(Math.random() * 9);
    //字符串拼接 将每次随机的字符 进行拼接
    code += random[index];
  }
  //将拼接好的字符串赋值给展示的code
  return code;
}

////表单操作事件

let formStrategy = {
  emp: dialogEmpConfirmEvent,
  pos: dialogPostConfirmEvent,
  org: dialogOrgConfirmEvent,
  para: dialogParameterConfirmEvent,
  unit: dialogUnitConfirmEvent,
};

///弹出框返回赋值
function dialogEmpConfirmEvent(that, res) {
  if (res.key.aCode != undefined && res.key.rowTag != undefined) {
    var fields = that.formdata[res.key.aCode].tables.filter(
      (o) => o.rowTag == res.key.rowTag
    )[0];
    if (fields != null && fields != undefined) {
      fields[res.key.fieldKey].fieldValues = [];
      fields[res.key.fieldKey].fieldValue = [];
      res.result.forEach((re) => {
        fields[res.key.fieldKey].fieldValues.push({
          value: re.empId,
          cnName: re.cnName,
          enName: re.enName,
        });
        fields[res.key.fieldKey].fieldValue.push(re.empId);
      });
    }
  } else {
    that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValues = [];
    that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValue = [];
    res.result.forEach((re) => {
      that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValues.push({
        value: re.empId,
        cnName: re.cnName,
        enName: re.enName,
      });
      that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValue.push(
        re.empId
      );
    });
  }
  ///更换申请人时获取数据
  if (that.applyEmpNameKey == res.key.fieldKey)
    that.initData(that.form, res.result[0].empId);
}
///弹出职位框
function dialogPostConfirmEvent(that, res) {
  if (res.key.aCode != undefined && res.key.rowTag != undefined) {
    var fields = that.formdata[res.key.aCode].tables.filter(
      (o) => o.rowTag == res.key.rowTag
    )[0];
    if (fields != null && fields != undefined) {
      fields[res.key.fieldKey].fieldValues = [];
      fields[res.key.fieldKey].fieldValue = [];
      res.result.forEach((re) => {
        fields[res.key.fieldKey].fieldValues.push({
          value: re.positionId,
          cnName: re.cnName,
          enName: re.enName,
        });
        fields[res.key.fieldKey].fieldValue.push(re.positionId);
      });
    }
  } else {
    that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValues = [];
    that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValue = [];
    res.result.forEach((re) => {
      that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValues.push({
        value: re.positionId,
        cnName: re.cnName,
        enName: re.enName,
      });
      that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValue.push(
        re.positionId
      );
    });
  }
}
///弹出部门框
function dialogOrgConfirmEvent(that, res) {
  if (res.key.aCode != undefined && res.key.rowTag != undefined) {
    var fields = that.formdata[res.key.aCode].tables.filter(
      (o) => o.rowTag == res.key.rowTag
    )[0];
    if (fields != null && fields != undefined) {
      fields[res.key.fieldKey].fieldValues = [];
      fields[res.key.fieldKey].fieldValue = [];
      res.result.forEach((re) => {
        fields[res.key.fieldKey].fieldValues.push({
          value: re.orgId,
          cnName: re.cnName,
          enName: re.enName,
          parameterCode: re.orgCode,
        });
        fields[res.key.fieldKey].fieldValue.push(re.orgId);
      });
    }
  } else {
    that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValues = [];
    that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValue = [];
    res.result.forEach((re) => {
      that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValues.push({
        value: re.orgId,
        cnName: re.cnName,
        enName: re.enName,
        orgCode: re.orgCode,
      });
      that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValue.push(
        re.orgId
      );
    });
  }
}
function dialogParameterConfirmEvent(that, res) {
  if (res.key.aCode != undefined && res.key.rowTag != undefined) {
    let table = that.formdata[res.key.aCode].tables.filter(
      (o) => o.rowTag == res.key.rowTag
    )[0][res.key.fieldKey];
    table.fieldValues = [];
    table.fieldValue = [];
    res.result.forEach((re) => {
      table.fieldValues.push({
        value: re.parameterCode,
        cnName: re.cnName,
        enName: re.enName,
        parameterCode: re.parameterCode,
      });
      table.fieldValue.push(re.parameterCode);
    });
  } else {
    that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValues = [];
    that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValue = [];
    res.result.forEach((re) => {
      that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValues.push({
        value: re.parameterCode,
        cnName: re.cnName,
        enName: re.enName,
        parameterCode: re.parameterCode,
      });
      that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValue.push(
        re.parameterCode
      );
    });
  }
} ///弹出公司框
function dialogUnitConfirmEvent(that, res) {
  if (res.key.aCode != undefined && res.key.fieldTag != undefined) {
    let table = that.formdata[res.key.aCode].tables.filter(
      (o) => o.fieldTag == res.key.fieldTag
    );
    table.fieldValues = [];
    table.fieldValue = [];
    res.result.forEach((re) => {
      table.fieldValues.push({
        value: re.unitId,
        cnName: re.cnName,
        enName: re.enName,
        unitCode: re.unitCode,
      });
      table.fieldValue.push(re.unitId);
    });
  } else {
    that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValues = [];
    that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValue = [];
    res.result.forEach((re) => {
      that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValues.push({
        value: re.unitId,
        cnName: re.cnName,
        enName: re.enName,
        unitCode: re.unitCode,
      });
      that.formdata[res.key.aCode].data[res.key.fieldKey].fieldValue.push(
        re.unitId
      );
    });
  }
}
///清除常用参数值
function clearValue(value, item) {
  item.fieldValues = item.fieldValues.filter((o) => o.value !== value);
}

////任务处理
function getNextNodeInfo(parameter, that) {
  let url = that.apiEnginepath + "/v1.0/nextnode";
  reqVue.$Post(parameter, url, that.way).then(
    function(data) {
      if (data.status) {
        dialogNodeInfoEvent(parameter, that, data);
      } else {
        that.pageLoading = false;
        that.$message.error(data.message);
      }
    }.bind(that)
  );
}

///弹出选择节点和人员的弹出框
function dialogNodeInfoEvent(parameter, that, result) {
  console.log(parameter, that, result);
  if (result.body.judeNodeType !== 0) {
    that.$nextTick(function() {
      result.body.nextNode.forEach((element) => {
        if (element.approvalRangeType == 2) {
          element.nextStepApproverEmps = [];
          element.nextStepApproverEmpId = [];
        }
      });
      that.$refs.node.processType = parameter.processType;
      that.$refs.node.nextNodeInfo = result.body.nextNode;
      that.$refs.node.dialogNextNodeisible = true;
      that.$refs.node.parallelTask = result.body.judeNodeType;
      that.$refs.node.nextStepIds = [result.body.nextNode[0].nextStepId];
      that.$refs.node.nextStepId = result.body.nextNode[0].nextStepId;
    });
  } else {
    if (parameter.processType == 7)
      processCirculatedEvent(
        {
          eventType: "circulated",
          result: result.body.nextNode,
          isConfirm: true,
        },
        that
      );
    else
      processSumbitEvent(
        {
          eventType: "sumbit",
          result: result.body.nextNode,
          isConfirm: true,
        },
        that
      );
  }
}
///处理任务
function processEvent(res, that) {
  processCanleEvent(res, that);
  processSumbitEvent(res, that);
  processCirculatedEvent(res, that);
  processBackStepEvent(res, that);
}
///清除重复提交问题
function processCanleEvent(res, that) {
  if (res.eventType == "canle") {
    let url =
      "flowcenter/v1.0/clearrepeatkey/" +
      formData.secretKey +
      "/" +
      formData.taskId;
    reqVue.$Post(null, url, that.way).then(
      function(data) {
        if (data.status) {
          that.pageLoading = false;
        } else {
          that.pageLoading = false;
          that.$message.error(data.message);
        }
      }.bind(that)
    );
  }
}
///提交任务
function processSumbitEvent(res, that) {
  if (res.eventType == "sumbit") {
    if (res.isConfirm)
      that
        .$confirm(
          that.$t("flowi18n.flow_center_confirm_sumbit_info"),
          that.$t("i18n.confirm"),
          {
            type: "warning",
          }
        )
        .then(() => {
          processRunEvent(res, that);
        })
        .catch(() => {
          processCanleEvent({ eventType: "canle" }, that);
        });
    else processRunEvent(res, that);
  }
}
function processRunEvent(res, that) {
  formData.nodeInfo = res.result;
  formData.opinion =
    that.opinion == null ? "" : that.opinion.defaultValue || "";
  let url = that.apiEnginepath + "/v2.0/approval/";
  reqVue.$Post(formData, url, that.way).then(
    function(data) {
      if (data.status) {
        ///不返回数据说明不需要跳过
        if (data.body == null) {
          that.$message.success(data.message);
          setTimeout(() => {
            that.pageLoading = false;
            that.$store.commit("closeCurrentPage", that.$route.fullPath);
            that.$router.push({
              path: "/flowcenter",
              query: { callType: that.$route.query.callType },
            });
          }, 1000);
        } else {
          formData.taskId = data.body.currentTaskId;
          skipNode(that);
        }
      } else {
        that.$message.error(data.message);
        that.pageLoading = false;
      }
    }.bind(that)
  );
}
///进行跳过任务处理
function skipNode(that) {
  let url = that.apiEnginepath + "/v2.0/skipnodeinfo";
  reqVue.$Post(formData, url, that.way).then(
    function(data) {
      if (data.status) {
        ///不需要跳过
        if (data.code == 500527) {
          that.pageLoading = false;
          that.$store.commit("closeCurrentPage", that.$route.fullPath);
          that.$router.push({
            path: "/flowcenter",
            query: { callType: that.$route.query.callType },
          });
          ///无人跳过功能
        } else if (data.code == 500528) {
          dialogNodeInfoEvent(formData, that, data);
        } else {
          formData.nodeInfo = data.body.nextNode;
          let url = that.apiEnginepath + "/v2.0/approval/";
          reqVue.$Post(formData, url, that.way).then(
            function(data) {
              if (data.status) {
                ///不返回数据说明不需要跳过
                if (data.body == null) {
                  that.$message.success(data.message);
                  setTimeout(() => {
                    that.pageLoading = false;
                    that.$store.commit(
                      "closeCurrentPage",
                      that.$route.fullPath
                    );
                    that.$router.push({
                      path: "/flowcenter",
                      query: { callType: that.$route.query.callType },
                    });
                  }, 1000);
                } else {
                  formData.taskId = data.body.currentTaskId;
                  skipNode(that);
                }
              } else {
                that.$message.error(data.message);
                that.pageLoading = false;
              }
            }.bind(that)
          );
        }
      } else {
        that.pageLoading = false;
        that.$message.error(data.message);
      }
    }.bind(that)
  );
}
///传阅任务
function processCirculatedEvent(res, that) {
  if (res.eventType == "circulated") {
    formData.nodeInfo = res.result;
    formData.opinion =
      that.opinion == null ? "" : that.opinion.defaultValue || "";
    let url = that.apiEnginepath + "/v2.0/circulated/";
    reqVue.$Post(formData, url, that.way).then(
      function(data) {
        if (data.status) {
          that.$message.success(data.message);
          setTimeout(() => {
            that.pageLoading = false;
            that.$store.commit("closeCurrentPage", that.$route.fullPath);
            that.$router.push({
              path: "/flowcenter",
              query: { callType: that.$route.query.callType },
            });
          }, 1000);
        } else {
          that.$message.error(data.message);
          that.pageLoading = false;
        }
      }.bind(that)
    );
  }
}
///退回至具体步骤任务处理
function processBackStepEvent(res, that) {
  if (res.eventType == "backnode") {
    formData.nodeInfo = res.result;
    formData.opinion =
      that.opinion == null ? "" : that.opinion.defaultValue || "";
    let url = that.apiEnginepath + "/v2.0/backstep/";
    reqVue.$Post(formData, url, that.way).then(
      function(data) {
        if (data.status) {
          that.$message.success(data.message);
          setTimeout(() => {
            that.pageLoading = false;
            that.$store.commit("closeCurrentPage", that.$route.fullPath);
            that.$router.push({
              path: "/flowcenter",
              query: { callType: that.$route.query.callType },
            });
          }, 1000);
        } else {
          that.$message.error(data.message);
          that.pageLoading = false;
        }
      }.bind(that)
    );
  }
}

////任务处理结束
export default {
  ///执行任务的方法
  $flowEvent: function(btn, that) {
    that.pageLoading = true;
    formData = {
      flowId: that.$route.query.flowId,
      flowVersionId: that.$route.query.flowVersionId,
      formId: that.$route.query.formId,
      FormVersionId: that.$route.query.formVersionId,
      ApprovalType: that.$route.query.approvalType,
      taskId: that.$route.query.taskId,
      model: that.formdata,
      secretKey:
        that.$route.query.flowId +
        "$" +
        that.$route.query.flowVersionId +
        "$" +
        that.secretKey +
        "$" +
        that.$route.query.formId +
        "$" +
        that.$route.query.formVersionId,
      opinion: "",
    };
    flowStrategy[btn.btnCode](btn, that);
  },
  ///随机生成编码
  $createCode: function(codeLength) {
    return createCode(codeLength);
  },
  ///表单处理事件
  $formDialogEvent: function(that, results, eventCode) {
    formStrategy[eventCode](that, results);
  },
  ///清除常用参数值
  $clearValue(value, item) {
    clearValue(value, item);
  },
  ///处理任务
  $processEvent: function(res, that) {
    processEvent(res, that);
  },
  name: "flowutils",
};
</script>
